/*
 * Copyright (C) 2010-2011 Enrique Lara (enrique.posix2.lara@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package app.timetogo;

import android.app.Activity;

import android.content.Context;

import android.os.Bundle;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import app.timetogo.model.Agency;
import app.timetogo.model.App;
import app.timetogo.model.Stop;
import app.timetogo.model.Vehicle;

import app.timetogo.provider.Tables.Alarms;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.TreeSet;

import org.xml.sax.SAXException;

public final class StopViewer extends Activity {
    private Stop s = null;
    private Agency agency = null;

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.stop_view);

        final int agencyId = getIntent().getExtras().getInt(Alarms.AGENCY_ID);
        final String apiCode = getIntent().getExtras().getString(Alarms.STOP);

        agency = App.getAgency(agencyId, this);
        s = agency.getStopByCode(apiCode);

        final TextView stationView = (TextView) findViewById(R.id.station_name);
        stationView.setText(s.getName());

        try {
            final ArrayList<Vehicle> vehicles = agency.getVehicles(s);

            final TreeSet<Vehicle> group1 = new TreeSet<Vehicle>(new Vehicle.VehicleComparator());
            final TreeSet<Vehicle> group2 = new TreeSet<Vehicle>(new Vehicle.VehicleComparator());

            for (final Vehicle v : vehicles) {
                switch (v.getGroup()) {
                    case 1:
                        group1.add(v);

                        break;

                    case 2:
                        group2.add(v);

                        break;

                    default:

                    //XXX logit
                }
            }

            final VehicleAdapter adapter1 = new VehicleAdapter(this, group1, group2);
            final ListView trainsView1 = (ListView) findViewById(R.id.trains1);
            trainsView1.setAdapter(adapter1);
        } catch (final IOException e) {
            App.showError(this, "Problems parsing obtaining vehicle data", e);
        } catch (final SAXException e) {
            App.showError(this, "Problems parsing obtaining vehicle data", e);
        } catch (final Throwable t) {
            final StringWriter msg = new StringWriter();
            final PrintWriter err = new PrintWriter(msg);
            t.printStackTrace(err);
            stationView.setText(msg.toString());
        }

        /*
        TextView dateView = (TextView) findViewById(R.id.last_updated);
        String format = android.text.format.DateFormat.is24HourFormat(this) ? T24 : T12;
        CharSequence dateStr = android.text.format.DateFormat.format(format, new Date());//XXX consider capturing response time in API.
        dateView.setText(dateStr);
        */
    }

//    private static final String T12 = "h:mm:ss aa zz";
//    private static final String T24 = "kk:mm:ss zz";

    //XXX Make generic for #n groups?
    private class VehicleAdapter extends BaseAdapter {
        private final Context context;
        private final Vehicle[] group1;
        private final Vehicle[] group2;
        private final int n1;
        private final int n2;

        public VehicleAdapter(final Context context, final TreeSet<Vehicle> group1, final TreeSet<Vehicle> group2) {
            this.context = context;
            this.group1 = group1.toArray(new Vehicle[group1.size()]);
            this.group2 = group2.toArray(new Vehicle[group2.size()]);

            this.n1 = group1.size();
            this.n2 = group2.size();
        }

        public int getCount() {
            return 2 + n1 + n2;
        }

        public Object getItem(final int position) {
            if (position == 0) {
                return "DIVIDER";
            } else if (position <= n1) {
                return group1[position - 1];
            } else if (position == (n1 + 1)) {
                return "DIVIDER";
            } else {
                //9
                // DIV 0 1 2 DIV 0 1 2 3
                //   0 1 2 3   4 5 6 7 8
                return group2[position - (n1 + 2)];
            }
        }

        public long getItemId(final int position) {
            return position;
        }

        public View getView(final int position, final View v, final ViewGroup parent) {
            if ((position == 0) || (position == (n1 + 1))) {
                final View view = LayoutInflater.from(context).inflate(R.layout.list_item_divider, parent, false);

                return view;
            }

            final View view = LayoutInflater.from(context).inflate(R.layout.list_item_station, parent, false);
            final Vehicle t = (Vehicle) getItem(position);
            Android.cptxt(view, R.id.headsign, t.getDestinationName());

            if (t.getMinutes() != 0) {
                Android.cptxt(view, R.id.minutes, Integer.toString(t.getMinutes()));
            } else {
                Android.cptxt(view, R.id.minutes, t.getStatus());
            }

            final ImageView line = (ImageView) view.findViewById(R.id.line);
            line.setImageResource(t.getRoute().getImageId());

            return view;
        }
    }
}
